# ~*~ coding: utf-8 ~*~
import sys
import json
import os
import importlib
import configparser
import requests
import socket
importlib.reload(sys)

#加载django
#import django
#CMDB_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#sys.path.append(CMDB_PATH)
#os.environ.setdefault("DJANGO_SETTINGS_MODULE","syscmdb.settings")
#django.setup()


from paramiko_api import *
from mailers import SendMessages
from DingDing import SendMs
from configs import *
from Log import logger
#from mysqldb import DbSearch

from celery import Celery,platforms
platforms.C_FORCE_ROOT = True
app = Celery('butterfly',backend=CELERY_RESULT_BACKEND,broker=BROKER_URL,include=['tasks'],)
app.conf.CELERY_IGNORE_RESULT = False
#json报错,注释了
#app.conf.CELERY_ACCEPT_CONTENT = [CELERY_ACCEPT_CONTENT]
app.conf.CELERY_TASK_SERIALIZER = CELERY_TASK_SERIALIZER
app.conf.CELERY_RESULT_SERIALIZER = CELERY_RESULT_SERIALIZER
app.conf.CELERY_TIMEZONE = CELERY_TIMEZONE


#日志
@app.task
def RemoteDispatch(assets,cmd,MSG):

	alert_type = MSG['alert_type']
	alert_type_link = MSG['alert_type_link']
	user = MSG['user']

	sm = SSHConnection(assets)
	result = sm.run_cmd(cmd)

	if result['stdout'] != '':
		mes = '自愈信息是%s'%(result['stdout'])
		logger.info(mes)
		ACCESS_LIST=[mes]
		ERROR_LIST = []
		if alert_type == 1:
			SendMessages(alert_type_link, ACCESS_LIST, ERROR_LIST, user)
		if alert_type == 2:
			SendMs(alert_type_link, mes)


		return 0

	if result['stderr'] != '':
		mes = '自愈错误信息是%s'%(result['stderr'])
		logger.info(mes)
		ACCESS_LIST = []
		ERROR_LIST = [mes]
		if alert_type == 1:
			SendMessages(alert_type_link, ACCESS_LIST, ERROR_LIST, user)
		if alert_type == 2:
			SendMs(alert_type_link, mes)
		return 1


